import hashlib
import requests
import time
import random
import math
import re


def first_key():
    mobile_key1 = f'x-agent=web&x-device-id=0c4c326258f0da1c&x-language=cn&x-timestamp={int(time.time() * 1000)}&salt=ndksyr9834@#$32ndsfu'
    time_key1 = f'timestamp={int(time.time() * 1000)}&salt=ndksyr9834@#$32ndsfu'
    first_res = hashlib.md5(mobile_key1.encode()).hexdigest() + hashlib.md5(
        time_key1.encode()).hexdigest()
    new_number = "".join(re.findall(r'\d+', first_res))

    return new_number


def get_key(item_code, timestamp):
    mobile_key2 = f'x-agent=web&x-device-id=0c4c326258f0da1c&x-language=cn&x-timestamp={int(time.time() * 1000)}&salt=ndksyr9834@#$32ndsfu'
    second_key = f'item_code={item_code}&timestamp={timestamp}&salt=ndksyr9834@#$32ndsfu'
    return hashlib.md5(mobile_key2.encode()).hexdigest() + hashlib.md5(
        second_key.encode()).hexdigest()


def get_product(procode, sign, timestamp):

    headers = {
        'Origin': 'https://www.macklin.cn',
        'Referer': 'https://www.macklin.cn/',
        'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0',
        'sign': sign,
    }

    json_data = {
        'item_code': procode,
        'timestamp': timestamp,
    }

    response = requests.post('https://api.macklin.cn/api/product/info',
                             headers=headers,
                             json=json_data)

    print(response.status_code)
    print(response.json())


def get_server_timestamp():
    '''
    获取服务器时间戳
    '''
    server_url = "https://api.macklin.cn/api/timestamp"
    headers = {
        'Content-Type':
        'application/json',
        'Origin':
        'https://www.macklin.cn',
        'Referer':
        'https://www.macklin.cn/',
        'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0',
    }
    resp = requests.get(server_url, headers=headers)

    if resp.json()['code'] == 200:
        return resp.json()['data']['timestamp']
    else:
        raise Exception("获取服务器时间戳出错")


if __name__ == "__main__":
    # procode = 'T818517'
    # first_res = first_key()
    # sign_res = get_key(procode, first_res)
    # get_product(procode,sign_res,first_res)

    server_time = get_server_timestamp()
    print(server_time)
